package org.ufinity.hsms.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.client.HttpResponseException;
//import org.apache.commons.httpclient.HttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;

import java.util.HashMap;
import java.util.List;

public class ZabbixApiClient 
{
	//private static String ZABBIX_API_URL = "http://192.168.1.242/anhuipostal/api_jsonrpc.php";
	//private static String ZABBIX_API_URL = "http://61.190.16.250:9024/anhuipostal/api_jsonrpc.php";
	private static String ZABBIX_API_URL = "http://180.168.7.46:7052/30iMonitor/api_jsonrpc.php";
    public static String SessionId = "";
    
    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
	public static JSONObject MakeRequest(int id, String method, boolean needAuth, String params) throws JSONException,FileNotFoundException, UnsupportedEncodingException
	{
		JSONObject obj = null;
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost postMethod = new HttpPost(ZABBIX_API_URL);
		//postMethod.setHeader(name, value)
		postMethod.setHeader("Content-Type", "application/json-rpc");
		StringBuilder buf = new StringBuilder();
		buf.append("{");
		buf.append("\"jsonrpc\":\"2.0\",");
		buf.append("\"method\":\"" + method + "\",");
		buf.append("\"params\":" + params + ",");
		if (needAuth)
		{
			buf.append("\"auth\":\"" + SessionId + "\",");
		}
		
		buf.append("\"id\":\"" + id + "\"");
		buf.append("}");
		
        // Create json object for apiinfo.version 
        JSONObject jsonObj = new JSONObject(buf.toString());
        
        android.util.Log.v("request", buf.toString());
        
        
        postMethod.setEntity(new ByteArrayEntity(
        		jsonObj.toString().getBytes("UTF8")));

        // Put the json object as input stream into request body 
        //postMethod.setRequestBody(fromString(jsonObj.toString()));  

        String strResponse = "";
        
        try 
        {
        	
           // HttpResponse response = client.execute(postMethod);
          
           // android.util.Log.v("response", response.getEntity().getContent().toString());
            
            HttpResponse httpResponse = client.execute(postMethod);
            HttpEntity entity = httpResponse.getEntity();
            InputStream is = entity.getContent();
            
            String strResult = convertStreamToString(is);
            // Work with the data using methods like... 
           //remove the head of BOM of the php
            if(strResult != null
              && strResult.length() != 0
              && strResult.indexOf("{")!=-1
              && strResult.lastIndexOf("}")!=-1)
            {
            	strResult = strResult.substring(strResult.indexOf("{"), strResult.lastIndexOf("}")+1);
            }
            obj = new JSONObject(strResult); 
        } 
        catch (HttpResponseException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }              
        Log.i("====>", obj.toString());
        return obj;
	}
	
	public static JSONObject MakeRequest(int id, String method, boolean needAuth, String params, String sessionId) throws JSONException,FileNotFoundException, UnsupportedEncodingException
	{
		JSONObject obj = null;
		DefaultHttpClient client = new DefaultHttpClient();
		
		
		
		HttpPost postMethod = new HttpPost(ZABBIX_API_URL);
		//PostMethod postMethod = new PostMethod(ZABBIX_API_URL);
		postMethod.setHeader("Content-Type", "application/json-rpc");
        
		StringBuilder buf = new StringBuilder();
		buf.append("{");
		buf.append("\"jsonrpc\":\"2.0\",");
		buf.append("\"method\":\"" + method + "\",");
		buf.append("\"params\":" + params + ",");
		
		if (needAuth)
		{
			buf.append("\"auth\":\"" + sessionId + "\",");
		}
		
		buf.append("\"id\":\"" + id + "\"");
		buf.append("}");
		
        // Create json object for apiinfo.version 
        JSONObject jsonObj = new JSONObject(buf.toString());
          
        // Put the json object as input stream into request body 
       // postMethod.setRequestBody(fromString(jsonObj.toString()));  
        postMethod.setEntity(new ByteArrayEntity(
        		jsonObj.toString().getBytes("UTF8")));  
        
        String strResponse = "";
        
        try 
        {
            HttpResponse httpResponse = client.execute(postMethod);
            HttpEntity entity = httpResponse.getEntity();
            InputStream is = entity.getContent();
            
            String strResult =convertStreamToString(is);
            // Work with the data using methods like...
            //remove the head of BOM of the php            
            if(strResult != null
              && strResult.length() != 0
              && strResult.indexOf("{")!=-1
              && strResult.lastIndexOf("}")!=-1)
            {
            	strResult = strResult.substring(strResult.indexOf("{"), strResult.lastIndexOf("}")+1);
            }
            obj = new JSONObject(strResult); 
        } 
        catch (HttpResponseException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }              
        
        return obj;
	}
	
	public static String getApiInfoVersion()
	{
		String retValue = "";
		
		try
		{
			JSONObject obj = MakeRequest(1, "apiinfo.version", false, "{}");
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	
	/**
	 * 登录
	 * @param username
	 * @param password
	 * @return
	 */
	public static String getAuthInfo(String username, String password)
	{
		String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"password\":\"" + password + "\",");
			params.append("\"user\":\"" + username + "\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(2, "user.authenticate", false, params.toString());
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			android.util.Log.v("error", e.getMessage());
			
		}
		
		return retValue;
	}
	
	public static void makeAcknowledgeRequest(String hostid)
	{
		String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"hostids\":[" + hostid + "]");
			params.append("}");
			
			JSONObject obj = MakeRequest(3, "Event.acknowledge", true, params.toString());
			retValue = obj.toString();
			
			System.out.println(retValue);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}		
	}
	
	/**
	 * 主机组列表
	 * @return
	 */
	public static JSONObject getHostGroup()
	{
		JSONObject obj = null;
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"output\":\"extend\",");
			params.append("\"sortfield\":\"name\"");
			params.append("}");
			
			obj = MakeRequest(3, "hostgroup.get", true, params.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	/**
	 * 设备列表(单个主机)
	 * @return
	 */
	public static JSONObject getHost(HashMap<String, String> map)
	{
		JSONObject obj = null;
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"output\":\"extend\",");
			
		/*	//原有的
			params.append("\"select_groups\":\"refer\"");
			params.append("}");*/
			
			//先有的
			params.append("\"filter\":{");
			params.append("\"host\":[");
			params.append("\""+map.get("group_name")+"\"");
			params.append("]");
			params.append("}");
			params.append("}");
			
			
			/*"filter": {
	            "host": [
	                "Linux 服务器组",
	                "Linux server"
	            ]
	        }*/

			
			obj = MakeRequest(Integer.parseInt(map.get("group_id")), "host.get", true, params.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	public static String getEventContent(List<String> triggerIdList)
	{
		String retValue = "";
		String triggerids = "";
		
		int n = triggerIdList.size();
		
		for (int i = 0; i < n-1; i++)
		{
			triggerids = triggerids + triggerIdList.get(i) + ",";
		}
		
		if (n > 0)
		{
			triggerids = triggerids + triggerIdList.get(n - 1);
		}
		
		//triggerIdList.
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"output\":\"extend\",");
			params.append("\"triggerids\":[" + triggerids + "],");
			
			params.append("\"expandDescription\":\"true\",");
			params.append("\"select_hosts\":\"refer\"");
			
			params.append("}");
			
			JSONObject obj = MakeRequest(6, "trigger.get", true, params.toString());
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	public static String getEventsByHostId(String hostid)
	{
		String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			//params.append("\"limit\":\"20\",");
			params.append("\"hostids\":[" + hostid + "],");
			params.append("\"select_hosts\":\"refer\",");
			params.append("\"sortorder\":\"DESC\",");
			params.append("\"output\":\"extend\",");
			params.append("\"select_triggers\":\"refer\",");
			params.append("\"sortfield\":\"clock\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(5, "event.get", true, params.toString());
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	public static String getCaculateNumber(String hostid,String eventType)
	{
        String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"nodeids\":\"0\",");
			params.append("\"output\":\"extend\",");
			params.append("\"hostids\":[" + hostid + "],");
			params.append("\"nopermissions\":\"true\",");
			params.append("\"value\":\""+eventType+"\"");//"1" is for common events,"2" is for alert events
			params.append("}");
			
			JSONObject obj = MakeRequest(5, "event.getCount", true, params.toString());
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;		
	}
	
	public static String getHistoryData(String itemid)
	{
		String retValue = "";
		
		try
		{
			long timeTill = System.currentTimeMillis() / 1000L;
			long timeFrom = timeTill - 3600;
			
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"history\":0,");
			params.append("\"itemids\":[" + itemid + "],");
			params.append("\"sortorder\":\"ASC\",");
			params.append("\"output\":\"extend\",");
			params.append("\"time_till\":" + timeTill + ",");
			params.append("\"time_from\":" + timeFrom + ",");
			params.append("\"sortfield\":\"clock\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(11, "history.get", true, params.toString());
			//JSONObject obj = MakeRequest(11, "history.get", true, params.toString(), "fdb3201b66804d3b9e240573e966d364");
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	public static String checkIsHaveGraphData(String itemid)
	{
		String retValue = "";
		
		try
		{			
			StringBuilder params = new StringBuilder();
			params.append("{");			
			params.append("\"itemid\":" + itemid + "");	
			params.append("}");
			
			JSONObject obj = MakeRequest(11, "graphItem.isGraph", true, params.toString());			
			retValue = obj.toString();						
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;		
	}
	
	public static String getTriggerContent(List<String> triggerIdList)
	{
		String retValue = "";
		String triggerids = "";
		
		int n = triggerIdList.size();
		
		for (int i = 0; i < n-1; i++)
		{
			triggerids = triggerids + triggerIdList.get(i) + ",";
		}
		
		if (n > 0)
		{
			triggerids = triggerids + triggerIdList.get(n - 1);
		}
		
		//triggerIdList.
		//android.util.Log.v("triggerids", triggerids);
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"object\":0,");
			params.append("\"triggerids\":[" + triggerids + "],");
			params.append("\"sortorder\":\"DESC\",");
			params.append("\"output\":\"extend\",");
			params.append("\"sortfield\":\"clock\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(6, "event.get", true, params.toString());
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	/**
	 *  总控面板
	 * @param hostid
	 * @return
	 */
	public static JSONObject getTriggersByHostId(String hostid)
	{
		hostid = "10198,10199,10200,10201,10203,10189,10190";
		JSONObject obj = null;
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"expandDescription\":\"true\",");
			params.append("\"hostids\":[" + hostid + "],");
			params.append("\"skipDependent\":1,");
			params.append("\"sortorder\":\"DESC\",");
			params.append("\"active\":1,");
			params.append("\"select_hosts\":\"refer\",");
			params.append("\"output\":\"extend\",");
			params.append("\"filter\":{\"value\":1},");
			params.append("\"monitored\":1,");
			params.append("\"sortfield\":\"lastchange\"");
			params.append("}");
			
			obj = MakeRequest(15, "trigger.get", true, params.toString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	public static String getRecentTriggersByHostId(String hostid)
	{
		String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"nodeids\":\"0\",");
			params.append("\"output\":\"extend\",");
			params.append("\"hostids\":\"" + hostid + "\",");
			params.append("\"filter\":array(),");			
			params.append("\"monitored\":\"1\",");
			params.append("\"skipDependent\":\"1\",");
			params.append("\"sortfield\":\"lastchange\",");
			params.append("\"sortorder\":\"DESC\",");
			params.append("\"limit\":\"1000\",");
			params.append("\"only_true\":\"1\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(5, "trigger.getFirstAcknowledge", true, params.toString());
			retValue = obj.toString();
			//System.out.println(retValue);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	public static String getTriggersByHostId(String hostid, String lastChangeSince, String lastChangeTill)
	{
		String retValue = "";
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"expandDescription\":\"true\",");
			params.append("\"lastChangeSince\":\"" + lastChangeSince + "\",");
			params.append("\"lastChangeTill\":\"" + lastChangeTill + "\",");
			params.append("\"hostids\":[" + hostid + "],");
			params.append("\"skipDependent\":0,");
			params.append("\"sortorder\":\"DESC\",");
			params.append("\"active\":1,");
			params.append("\"select_hosts\":\"refer\",");
			params.append("\"output\":\"extend\",");
			params.append("\"filter\":{\"value\":1},");
			params.append("\"monitored\":1,");
			params.append("\"sortfield\":\"lastchange\"");
			params.append("}");
			
			android.util.Log.v("param", params.toString());
			
			JSONObject obj = MakeRequest(5, "trigger.get", true, params.toString());
			retValue = obj.toString();			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	/**
	 * 获取分类项
	 * @param hostid
	 * @return
	 */
	public static JSONObject getAllItemsByHostId(String hostid)
	{
		JSONObject obj = null;
		
		android.util.Log.v("hostid", hostid);
		
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"hostids\":[" + hostid + "],");
			params.append("\"select_applications\":\"refer\",");
			params.append("\"expandDescription\":\"true\",");
			params.append("\"output\":\"extend\",");
			params.append("\"filter\":{\"status\":0}");
			params.append("}");
			
			obj = MakeRequest(5, "item.get", true, params.toString());
			//JSONObject obj = MakeRequest(5, "item.get", true, params.toString(), "fdb3201b66804d3b9e240573e966d364");
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
	
	public static String getAllApps(List<String> appIdList)
	{
		String retValue = "";
		String appIds = "";
		
		int n = appIdList.size();
		
		for (int i = 0; i < n-1; i++)
		{
			appIds = appIds + appIdList.get(i) + ",";
		}
		
		if (n > 0)
		{
			appIds = appIds + appIdList.get(n - 1);
		}
		
		//triggerIdList.
		try
		{
			StringBuilder params = new StringBuilder();
			params.append("{");
			params.append("\"sortorder\":\"ASC\",");
			params.append("\"output\":\"extend\",");
			params.append("\"applicationids\":[" + appIds + "],");
			params.append("\"sortfield\":\"name\"");
			params.append("}");
			
			JSONObject obj = MakeRequest(6, "application.get", true, params.toString());
			//JSONObject obj = MakeRequest(6, "application.get", true, params.toString(), "fdb3201b66804d3b9e240573e966d364");
			retValue = obj.toString();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return retValue;
	}
	
	public static InputStream fromString(String str) throws UnsupportedEncodingException 
	{
        byte[] bytes = str.getBytes("UTF-8");
        return new ByteArrayInputStream(bytes);
	}
}
